package org.home.millionaire;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Game_CallFriend extends Activity {
	EditText txtPhoneNumber;

	Button btnStartCall;
	Button btnClose;

	protected boolean _active = true;
	protected int _callTime = 5000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.callfriend);
		txtPhoneNumber = (EditText) findViewById(R.id.txtPhoneNumber);

		btnStartCall = (Button) findViewById(R.id.btnStartCall);
		btnClose = (Button) findViewById(R.id.btnClose);

		btnStartCall.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				makeCall();
			}
		});

		btnClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

	}

	private void makeCall() {
		PhoneCallListener phoneCallListener = new PhoneCallListener();
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(phoneCallListener,
				PhoneStateListener.LISTEN_CALL_STATE);

		String PhoneNumber = txtPhoneNumber.getText().toString();
		Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
				+ PhoneNumber));
		startActivity(callIntent);
	}

	private class PhoneCallListener extends PhoneStateListener {
		private boolean isPhoneCalling = false;

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			super.onCallStateChanged(state, incomingNumber);

			if (TelephonyManager.CALL_STATE_RINGING == state) {

			}

			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				isPhoneCalling = true;

			}

			if (TelephonyManager.CALL_STATE_IDLE == state) {
				if (isPhoneCalling) {
					/*
					 * Intent intent = getBaseContext().getPackageManager()
					 * .getLaunchIntentForPackage(
					 * getBaseContext().getPackageName());
					 * intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					 */

					Intent intent = getBaseContext().getPackageManager()
							.getLaunchIntentForPackage(getCallingPackage());
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

					startActivity(intent);

					isPhoneCalling = false;
				}
			}
		}
	}
}
